package com.shuke.sk_worm.tool.hiskpi.Impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.shuke.sk_worm.consts.ShopPlatformEnum;
import com.shuke.sk_worm.domain.HisKpi;
import com.shuke.sk_worm.service.HisKpiService;
import com.shuke.sk_worm.vo.PingduoduoDataVo;
import com.shuke.sk_worm.vo.ShopInfoListVo;
import com.shuke.sk_worm.vo.TaobaoDataVo;
import com.shuke.sk_worm.vo.TaobaoTimeDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class TaobaoShopImpl extends ShopDataImpl {

    private String dataUrl = "https://kf.topchitu.com/api/custom/report/kpi?dateType=dateRange&from=%s&to=%s&queryDateType=DAY&filterDays=&exportType=CUSTOM_WW_KPI&showDelayData=true&kpiType=ww&reportId=624&handleSubmit=true&customExport=false&wangwangExpandColumns=last_group_name,employee_name";

    private String timeUrl = "https://kf.topchitu.com/api/employee-kpi/workload?dateType=dateRange&from=%s&to=%s&queryDateType=DAY&filterDays=&exportType=WW_WORKLOAD&showDelayData=true&kpiType=ww&queryAllWangwang=true&handleSubmit=true&customExport=false&wangwangExpandColumns=last_group_name,employee_name";

    @Autowired
    private HisKpiService hisKpiService;

    public List<HisKpi> getUrlHisData(Date date, String cookie, List<String> shopAccounts, ShopInfoListVo shop){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        Long timestamp = date.getTime();
        //将时间转换指定格式的日期
        String terDate = f.format(timestamp);

        String time = sdf.format(timestamp);

        String url = String.format(dataUrl, time, time);

        String timeUrl = String.format(this.timeUrl, time, time);

        List<HisKpi> hisKpis = new ArrayList<>();

        //替换掉一些特殊的字符
        cookie = cookie.replaceAll("\n", "").replaceAll("\\s", "");
        String data = HttpRequest.get(url).header("Cookie", cookie).execute().body();

        JSONObject result = JSONUtil.parseObj(data);

        List<TaobaoDataVo> taobaoDatas = JSONUtil.toList(JSONUtil.parseArray(result.get("valueList")), TaobaoDataVo.class);

        taobaoDatas.forEach(his->{
            if (shopAccounts.contains(his.getShow_name())){
                HisKpi hisKpi = new HisKpi();

                hisKpi.setStaffName(his.getEmployee_name());
                hisKpi.setStaffUsername(his.getShow_name());
                hisKpi.setLaborUserAmount(his.getService_num());
                hisKpi.setInquirerAmount(his.getConsult_num());
                hisKpi.setPlatform(ShopPlatformEnum.TAOBAO);
                hisKpi.setInsertTime(terDate);
                hisKpi.setInsertTimestamp(timestamp);
                hisKpi.setUserId(shop.getUserId());
                hisKpi.setUserName(shop.getUserName());
                hisKpi.setShopId(shop.getId());
                hisKpi.setShopName(shop.getName());
                hisKpi.setUserIds(shop.getUserIds());
                hisKpi.setDeptId(shop.getDeptId());
                hisKpi.setDeptIds(shop.getDeptIds());
                hisKpi.setDeptNames(shop.getDeptNames());
                hisKpi.setPlatform(ShopPlatformEnum.TAOBAO);
                hisKpi.setBusinessManagerIds(shop.getBusinessManagerIds());
                hisKpi.setBusinessManagerNames(shop.getBusinessManagerNames());
                hisKpi.setBaseManagerIds(shop.getBaseManagerIds());
                hisKpi.setBaseManagerNames(shop.getBaseManagerNames());
                hisKpi.setThreeMinResponseRate("-");
                hisKpi.setThreeMinResponseConRate("-");
                if (his.getAsk_today_final_paid_succrate() != null){
                    hisKpi.setInquiryConversionRate(
                            String.valueOf(his.getAsk_today_final_paid_succrate().multiply(new BigDecimal(100)))
                    );
                }
                if (his.getAvg_total_reply_cost() != null){
                    hisKpi.setAvgResponseDuration(his.getAvg_total_reply_cost());
                }else{
                    hisKpi.setAvgResponseDuration("-");
                }

                if (his.getNew_customer_satisfied_rate() != null){
                    BigDecimal statisfied = his.getNew_customer_satisfied_rate().multiply(new BigDecimal(100));

                    hisKpi.setSatisfactionRate(String.valueOf(statisfied));
                    hisKpi.setDissatisfactionRate(
                            String.valueOf(new BigDecimal(100).subtract(statisfied))
                    );
                }else{
                    hisKpi.setSatisfactionRate("-");
                    hisKpi.setDissatisfactionRate("-");
                }

                hisKpis.add(hisKpi);
            }
        });

        String timeData = HttpRequest.get(timeUrl).header("Cookie", cookie).execute().body();

        JSONObject result1 = JSONUtil.parseObj(timeData);

        List<TaobaoTimeDataVo> taobaoDataTimes = JSONUtil.toList(JSONUtil.parseArray(result1.get("valueList")), TaobaoTimeDataVo.class);


        for (HisKpi hisKpi : hisKpis) {

            for (TaobaoTimeDataVo vo : taobaoDataTimes){
                if (hisKpi.getStaffUsername().equals(vo.getShow_name())){
                    if (vo.getResponse_three_minute_rate() != null){
                        BigDecimal threeResponse = vo.getResponse_three_minute_rate().multiply(new BigDecimal(100));
                        hisKpi.setThreeMinResponseRate(String.valueOf(threeResponse));
                        hisKpi.setThreeMinResponseConRate(String.valueOf(threeResponse));
                    }
                    break;
                }

            }
        }

        return hisKpis;
    }


    @Override
    public void hiskpi(List<ShopInfoListVo> shopInfoList, Map<Long,String> shopCookie, Date date){
        if (shopInfoList.isEmpty()){
            return;
        }

        for(ShopInfoListVo shop : shopInfoList){
            if (!shopCookie.containsKey(shop.getId())) {
                logger.info("店铺ID :" + shop.getId() + "未获取到Token");
                continue;
            }

            //账号信息
            List<String> shopAccounts = shop.getAccountInfos().stream().map(vo->{
                return  vo.getShopAccount().trim();
            }).collect(Collectors.toList());

            //昨日的数据
            List<HisKpi> yesterData = getUrlHisData(date, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!yesterData.isEmpty()){
                hisKpiService.batchInsertData(yesterData);
            }

            //24小时前的数据
            Date fourDay = DateUtil.offsetDay(date, -1);
            List<HisKpi> fourData =  getUrlHisData(fourDay, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!fourData.isEmpty()){
                hisKpiService.batchInsertData(fourData);
            }

            Date eightDay = DateUtil.offsetDay(fourDay, -1);
            List<HisKpi> eightData = getUrlHisData(eightDay, shopCookie.get(shop.getId()), shopAccounts, shop);
            if (!eightData.isEmpty()){
                //保存数据
                hisKpiService.batchInsertData(eightData);
            }
        }
    }
}
